import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/launch_util.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/mine/logistics.dart';
import 'package:gzmall_app/mine/order_details.dart';
import 'package:gzmall_app/model/order.dart';
import 'package:gzmall_app/model/order_item.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:gzmall_app/shoppping_cart/buy_success.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:gzmall_app/model/wechat_pay_info.dart';
import 'package:gzmall_app/mine/order_product_comment_page.dart';

class OrderListWidget extends StatefulWidget {
  String state;

  OrderListWidget(this.state);

  @override
  State<StatefulWidget> createState() => OrderListWidgetState(state);
}

class OrderListWidgetState extends State<OrderListWidget> {
  String state;

  List<Order> _orders = [];

  int _currentIndex;
  String _currentState;

  int _curPage = 1;
  RefreshListView _refreshListView;
  bool _showEmpty = false;

  OrderListWidgetState(this.state);

  @override
  void initState() {
    super.initState();
    fluwx.registerWxApi(appId: Api.wxAppId);
    fluwx.weChatResponseEventHandler.listen((data) {
      if (data is fluwx.WeChatPaymentResponse) {
        print("<fluwx> fluwx.weChatResponseEventHandler.listen");
        print("<fluwx> data.type " + data.type.toString());
        print("<fluwx> data.errCode " + data.errCode.toString());
        print("<fluwx> data.extData " + data.extData.toString());

        if (data != null && data.errCode != null) {
          switch (data.errCode) {
            case 0:
              // 成功 展示成功页面
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new BuySuccessPage(
                    _orders[_currentIndex].totalFee.toString(),
                    _orders[_currentIndex].id.toString());
              })).then((value) {
                Navigator.of(context).pop();
                _getOrders(state, 1);
              });
              break;
            case -1:
              // 错误 可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
              ToastUtil.showMessageToast(data.errStr ?? "微信支付错误");
              Navigator.of(context).pop();
              _getOrders(state, 1);
              break;
            case -2:
              // 用户取消 无需处理。发生场景：用户不支付了，点击取消，返回APP。
              break;
          }
        }
      }
    });

    _getData(1);
  }

  @override
  Widget build(BuildContext context) {
    _refreshListView = RefreshListView(
      enablePullUp: true,
      enablePullDown: true,
      onRefresh: _onRefresh,
      child: _createOrderListView(),
      showEmpty: _showEmpty,
      onReload: () {
        _getData(1);
      },
    );
    return _refreshListView;
  }

  _createOrderListView() {
    return ListView.builder(
      itemCount: _orders.length,
      itemBuilder: (context, index) {
        List<Widget> _ctlBtns = [];
        switch (_orders[index].state) {
          case "pending":
            _ctlBtns.add(Padding(
              padding: const EdgeInsets.only(right: 15.0),
              child: _getButtonView(
                  "取消订单", Colors.white, ColorCommon.black1, ColorCommon.grey5,
                  () {
                _currentIndex = index;
                // _currentState = _orders[index].state;
                // _updateOrder(_orders[index].id, "cancel");
                _cancelOrder(_orders[index].id);
              }),
            ));
            _ctlBtns.add(_getButtonView("立即付款", ColorCommon.primaryColor,
                Colors.white, ColorCommon.primaryColor, () {
              _currentIndex = index;
              // _currentState = _orders[index].state;
              // _updateOrder(_orders[index].id, "checkouted");
              _showPayWay(context);
            }));
            break;
          case "checkouted":
            // _ctlBtns.add(Padding(
            //   padding: const EdgeInsets.only(right: 0.0),
            //   child: _getButtonView(
            //       "提醒物流", Colors.white, ColorCommon.black1, ColorCommon.grey5,
            //       () {
            //     ToastUtil.showMessageToast("已帮您提醒物流, 请耐心等待");
            //   }),
            // ));
            break;
          case "sent":
            // _ctlBtns.add(Padding(
            //   padding: const EdgeInsets.only(right: 15.0),
            //   child: _getButtonView(
            //       "催物流", Colors.white, ColorCommon.black1, ColorCommon.grey5,
            //       () {
            //     ToastUtil.showMessageToast("已帮您催促物流, 请耐心等待");
            //   }),
            // ));
            _ctlBtns.add(Padding(
                padding: const EdgeInsets.only(right: 15.0),
                child: _getButtonView(
                    "查看物流", Colors.white, ColorCommon.black1, ColorCommon.grey5,
                    () {
                  Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                    return LogisticsPage(_orders[index].id);
                  })).then((v) {
                    _getOrders(state, 1);
                  });
                })));
            _ctlBtns.add(_getButtonView("确认收货", ColorCommon.primaryColor,
                Colors.white, ColorCommon.primaryColor, () {
              _currentIndex = index;
              // _currentState = _orders[index].state;
              // _updateOrder(_orders[index].id, "completed");
              _completeOrder(_orders[index].id);
            }));
            break;
          case "completed":
            _ctlBtns.add(Padding(
              padding: const EdgeInsets.only(right: 15.0),
              child: _getButtonView(
                  "删除订单", Colors.white, ColorCommon.black1, ColorCommon.grey5,
                  () {
                _deleteOrder(_orders[index].id);
              }),
            ));
            _ctlBtns.add(_getButtonView(
                "查看物流", Colors.white, ColorCommon.black1, ColorCommon.grey5,
                () {
              Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                return LogisticsPage(_orders[index].id);
              })).then((v) {
                _getOrders(state, 1);
              });
            }));
            if (_orders[index] != null && !_orders[index].isEvaluated) {
              _ctlBtns.add(Padding(
                  padding: const EdgeInsets.only(left: 15.0),
                  child: _getButtonView("评价", ColorCommon.primaryColor,
                      Colors.white, ColorCommon.primaryColor, () {
                    Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                      return OrderProductCommentPage(_orders[index].id);
                    })).then((v) {
                      _getOrders(state, 1);
                    });
                  })));
            }
            break;
          case "cancel":
            _ctlBtns.add(_getButtonView(
                "删除订单", Colors.white, ColorCommon.black1, ColorCommon.grey5,
                () {
              _currentIndex = index;
              _deleteOrder(_orders[index].id);
            }));
            break;
          default:
            break;
        }
        List<Widget> _itemWidget = [];
        if (_orders[index].items != null && _orders[index].items.length > 0) {
          _itemWidget = _orders[index]
              .items
              .map((item) => Container(
                    margin: const EdgeInsets.only(bottom: 1.0),
                    color: Colors.white,
                    padding: const EdgeInsets.only(
                        left: 15.0, right: 15.0, top: 10.0, bottom: 10.0),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        item != null && item.avatar != null
                            ? CachedNetworkImage(
                                width: 90.0,
                                height: 120.0,
                                imageUrl: item?.avatar,
                                fit: BoxFit.cover,
                              )
                            : Container(
                                color: ColorCommon.grey5,
                                width: 90.0,
                                height: 120.0,
                              ),
                        Expanded(
                          child: Container(
                            height: 120.0,
                            margin:
                                const EdgeInsets.only(left: 10.0, right: 10.0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Expanded(
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Expanded(
                                        child: Container(
                                          margin: const EdgeInsets.only(
                                              right: 30.0),
                                          child: Text(
                                            item?.name ?? "",
                                            style: TextStyle(
                                                fontSize: 15.0,
                                                color: ColorCommon.black1),
                                          ),
                                        ),
                                      ),
                                      Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.end,
                                        children: <Widget>[
                                          Text(
                                            "¥" + item?.fee.toString(),
                                            style: TextStyle(
                                                fontSize: 15.0,
                                                color: ColorCommon.grey4),
                                          ),
                                          Text(
                                            "x" + item?.quantity.toString(),
                                            style: TextStyle(
                                                fontSize: 15.0,
                                                color: ColorCommon.grey4),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                                // Row(
                                //   mainAxisAlignment: MainAxisAlignment.end,
                                //   children: <Widget>[
                                //     Text(
                                //       "查看产品使用说明",
                                //       style: TextStyle(
                                //           fontSize: 15.0,
                                //           color: ColorCommon.primaryColor),
                                //     ),
                                //   ],
                                // ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ))
              .toList();
        }
        return GestureDetector(
          onTap: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (_) {
              return OrderDetailsPage(id: _orders[index].id, type: state);
            })).then((v) {
              _getData(1);
            });
          },
          child: Column(
            children: <Widget>[
              Container(
                color: Colors.white,
                margin: const EdgeInsets.only(bottom: 1.0),
                padding: const EdgeInsets.only(
                    left: 15.0, right: 15.0, top: 10.0, bottom: 10.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        _orders[index]?.createdAt,
                        style: TextStyle(
                            fontSize: 15.0, color: ColorCommon.black1),
                      ),
                    ),
                    Text(
                      _orders[index]?.stateZh,
                      style: TextStyle(
                          fontSize: 15.0, color: ColorCommon.primaryColor),
                    ),
                    // GestureDetector(
                    //   child: Padding(
                    //     padding: const EdgeInsets.only(left: 10.0),
                    //     child: Image.asset(
                    //       "images/delete.png",
                    //       width: 15.0,
                    //       height: 15.0,
                    //     ),
                    //   ),
                    //   onTap: () {},
                    // ),
                  ],
                ),
              ),
              Column(
                children: _itemWidget,
              ),
              Container(
                color: Colors.white,
                padding: const EdgeInsets.only(
                    left: 15.0, right: 15.0, top: 10.0, bottom: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      "共" +
                          (_orders[index].items != null &&
                                  _orders[index].items.length > 0
                              ? _orders[index].items.length.toString()
                              : '0') +
                          "件 应付总额: ",
                      style:
                          TextStyle(fontSize: 15.0, color: ColorCommon.grey4),
                    ),
                    Text(
                      "¥ " + _orders[index].totalFee,
                      style: TextStyle(
                          fontSize: 15.0, color: ColorCommon.primaryColor),
                    ),
                  ],
                ),
              ),
              state != "after_sale"
                  ? Container(
                      color: Colors.white,
                      padding: const EdgeInsets.only(
                          left: 15.0, right: 15.0, top: 10.0, bottom: 10.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: _ctlBtns,
                      ),
                    )
                  : Container(),
            ],
          ),
        );
      },
    );
  }

  _getButtonView(String text, Color bgColor, Color contentColor,
      Color borderColor, GestureTapCallback onTap) {
    return Container(
      height: 30.0,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      decoration: BoxDecoration(
          color: bgColor,
          borderRadius: BorderRadius.circular(100.0),
          border: Border.all(color: borderColor, width: 1.0)),
      child: GestureDetector(
        onTap: onTap,
        child: Text(
          text,
          style: TextStyle(fontSize: 12.0, color: contentColor),
        ),
      ),
    );
  }

  _showPayWay(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Align(
                child: Text(
                  "确认付款",
                  style: TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                ),
              ),
              Align(
                alignment: Alignment.center,
                child: Padding(
                  padding: const EdgeInsets.only(top: 20.0, bottom: 20.0),
                  child: Text(
                    "¥ " + _orders[_currentIndex].totalFee.toString(),
                    style: TextStyle(
                      fontSize: 36.0,
                      color: ColorCommon.primaryColor,
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(bottom: 10.0),
                child: Text(
                  "付款方式",
                  style: TextStyle(fontSize: 15.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  padding: const EdgeInsets.only(top: 0.0),
                  children: <Widget>[
                    InkWell(
                      onTap: () {
                        List<String> _ids = [];
                        _ids.add(_orders[_currentIndex].id.toString());
                        if (_ids.length > 0) {
                          _getPayInfo(_ids, "moneybag");
                        } else {
                          ToastUtil.showMessageToast("下单错误, 请重试");
                        }
                      },
                      child: Container(
                        color: ColorCommon.grey5,
                        padding: const EdgeInsets.only(
                            left: 15.0, right: 15.0, bottom: 10.0, top: 10.0),
                        margin: const EdgeInsets.only(bottom: 10.0),
                        child: Row(children: <Widget>[
                          Image.asset(
                            "images/money_bag.png",
                            width: 30.0,
                            height: 30.0,
                          ),
                          Padding(
                            padding:
                                const EdgeInsets.only(left: 10.0, right: 10.0),
                            child: Text(
                              "钱包支付",
                              style: TextStyle(
                                  fontSize: 15.0, color: ColorCommon.black1),
                            ),
                          )
                        ]),
                      ),
                    ),
                    LaunchUtil.isInstallWeixin && !SettingUtil.isAppStoreAudit()
                        ? InkWell(
                            onTap: () {
                              List<String> _ids = [];
                              _ids.add(_orders[_currentIndex].id.toString());
                              if (_ids.length > 0) {
                                _getPayInfo(_ids, "wepay");
                              } else {
                                ToastUtil.showMessageToast("下单错误, 请重试");
                              }
                            },
                            child: Container(
                              color: ColorCommon.grey5,
                              padding: const EdgeInsets.only(
                                  left: 15.0,
                                  right: 15.0,
                                  bottom: 10.0,
                                  top: 10.0),
                              margin: const EdgeInsets.only(bottom: 10.0),
                              child: Row(children: <Widget>[
                                Image.asset(
                                  "images/wechat.png",
                                  width: 30.0,
                                  height: 30.0,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 10.0, right: 10.0),
                                  child: Text(
                                    "微信支付",
                                    style: TextStyle(
                                        fontSize: 15.0,
                                        color: ColorCommon.black1),
                                  ),
                                )
                              ]),
                            ),
                          )
                        : Container(),
                    LaunchUtil.isInstallAlipay && !SettingUtil.isAppStoreAudit()
                        ? InkWell(
                            onTap: () {
                              List<String> _ids = [];
                              _ids.add(_orders[_currentIndex].id.toString());
                              if (_ids.length > 0) {
                                _getPayInfo(_ids, "alipay");
                              } else {
                                ToastUtil.showMessageToast("下单错误, 请重试");
                              }
                            },
                            child: Container(
                              color: ColorCommon.grey5,
                              padding: const EdgeInsets.only(
                                  left: 15.0,
                                  right: 15.0,
                                  bottom: 10.0,
                                  top: 10.0),
                              margin: const EdgeInsets.only(bottom: 10.0),
                              child: Row(children: <Widget>[
                                Image.asset(
                                  "images/alipay.png",
                                  width: 30.0,
                                  height: 30.0,
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 10.0, right: 10.0),
                                  child: Text(
                                    "支付宝",
                                    style: TextStyle(
                                        fontSize: 15.0,
                                        color: ColorCommon.black1),
                                  ),
                                ),
                              ]),
                            ),
                          )
                        : Container(),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  void _onRefresh(bool up) {
    if (up) {
      _getData(1);
    } else {
      _getData(_curPage + 1);
    }
  }

  _getData(int page) {
    if (state == "after_sale") {
      _getOrderItems(page);
    } else {
      _getOrders(state, page);
    }
  }

  _getOrders(String state, int page) {
    bool isGetNew = page == 1;
    Map<String, String> params = {"state": state, "page": page.toString()};

    NetUtil.get(
        context,
        Api.orders,
        (data, message) {
          if (!mounted) return;
          _curPage = page;
          var _dataList = (data as List)
              ?.map((e) => e == null ? null : Order.fromJson(e))
              ?.toList();
          setState(() {
            _showEmpty =
                isGetNew && (_dataList == null || _dataList.length <= 0);
            if (isGetNew) {
              _orders = _dataList;
            } else {
              _orders.addAll(_dataList);
            }
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew,
                hasMore: _dataList != null && _dataList.length >= Api.pageSize);
          }
        },
        params: params,
        errorCallBack: (e) {
          setState(() {
            _showEmpty = isGetNew && (_orders == null || _orders.length <= 0);
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew);
          }
        });
  }

  _updateOrder(int id, String state) {
    FormData formData = new FormData.fromMap({
      "state": state,
    });

    NetUtil.put(
      context,
      Api.orders + "/" + id.toString(),
      (data, message) {
        ToastUtil.showMessageToast(message);

        if (!mounted) return;
        setState(() {
          _orders[_currentIndex].state = state;
          if (_currentState != state) {
            _orders.removeAt(_currentIndex);
          } else {
            _getOrders(state, 1);
          }
        });
      },
      params: formData,
    );
  }

  _getPayInfo(List<String> orderIds, String payMethod) async {
    Map<String, Object> params = {
      "orders": orderIds.join(","),
      "pay_method": payMethod,
    };

    NetUtil.post(context, Api.pay, (data, message) {
      ToastUtil.showMessageToast(message);

      if (payMethod == "wepay") {
        // 微信支付
        WechatPayInfo wechatPayInfo = WechatPayInfo.fromJson(data);
        fluwx
            .payWithWeChat(
                appId: wechatPayInfo.appid,
                partnerId: wechatPayInfo.partnerid,
                prepayId: wechatPayInfo.prepayid,
                packageValue: wechatPayInfo.package,
                nonceStr: wechatPayInfo.noncestr,
                timeStamp: int.parse(wechatPayInfo.timestamp),
                sign: wechatPayInfo.sign)
            .then((value) {
          print("<fluwx> then(value) ${value}");
        });
      } else if (payMethod == "alipay") {
        // 支付宝支付
        _callAlipay(data);
      } else if (payMethod == "moneybag") {
        Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          return new BuySuccessPage(_orders[_currentIndex].totalFee.toString(),
              _orders[_currentIndex].id.toString());
        })).then((value) {
          Navigator.of(context).pop();
          _getOrders(state, 1);
        });
      }
    }, params: params, isShowLoading: true);
  }

  _callAlipay(String payInfo) async {
    Map payResult = {};
    try {
      payResult = await tobias.aliPay(payInfo);
      print("<tobias> $payResult");
      if (payResult != null && payResult["resultStatus"] != null) {
        switch (payResult["resultStatus"].toString()) {
          case "9000":
            // 订单支付成功
            Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
              return new BuySuccessPage(
                  _orders[_currentIndex].totalFee.toString(),
                  _orders[_currentIndex].id.toString());
            })).then((value) {
              Navigator.of(context).pop();
              _getOrders(state, 1);
            });
            break;
          case "6001":
            // 用户中途取消
            break;
          default:
            // 支付失败
            ToastUtil.showMessageToast(payResult["memo"]);
            Navigator.of(context).pop();
            _getOrders(state, 1);
            break;
        }
      }
    } on Exception catch (e) {
      print("<tobias> $e");
    }
  }

  _cancelOrder(int id) {
    NetUtil.post(context, Api.orders + "/" + id.toString() + "/cancel",
        (data, message) {
      ToastUtil.showMessageToast(message);

      _getOrders(state, 1);
    }, isShowLoading: true);
  }

  _deleteOrder(int id) {
    NetUtil.delete(
      context,
      Api.orders + "/" + id.toString(),
      (data, message) {
        ToastUtil.showMessageToast(message);

        if (!mounted) return;
        setState(() {
          _orders.removeAt(_currentIndex);
        });
      },
    );
  }

  _completeOrder(int id) {
    NetUtil.post(context, Api.orders + "/" + id.toString() + "/complete",
        (data, message) {
      ToastUtil.showMessageToast(message);

      _getOrders(state, 1);
    }, isShowLoading: true);
  }

  _getOrderItems(int page) {
    bool isGetNew = page == 1;
    Map<String, String> params = {"page": page.toString()};
    NetUtil.get(
        context,
        Api.orderItemsAfterSales,
        (data, message) {
          if (!mounted) return;
          _curPage = page;
          var _dataList = (data as List)
              ?.map((e) => e == null ? null : Order.fromJson(e))
              ?.toList();
          setState(() {
            _showEmpty =
                isGetNew && (_dataList == null || _dataList.length <= 0);
            if (isGetNew) {
              _orders = _dataList;
            } else {
              _orders.addAll(_dataList);
            }
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew,
                hasMore: _dataList != null && _dataList.length >= Api.pageSize);
          }
        },
        params: params,
        errorCallBack: (e) {
          setState(() {
            _showEmpty = isGetNew && (_orders == null || _orders.length <= 0);
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew);
          }
        });
  }
}
